package cn.getech.data.development.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 检查网络是否连通
 */

@Slf4j
@Component
public class PingIpUtil {


    public static boolean ping(String ipAddress) {
        BufferedReader in = null;
        String pingCommand;
        Runtime r = Runtime.getRuntime();
        String osName = System.getProperty("os.name");
        // 组装命令，默认ping 4次
        if (osName.contains("Windows")) {
            pingCommand = "ping " + ipAddress;
        } else {
            pingCommand = "ping " + " -c4 " + ipAddress;
        }
        try {
            Process p = r.exec(pingCommand);
            if (p == null) {
                return false;
            }
            in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            int connectedCount = 0;
            String line;
            int num = 4;//检测2次
            while ((line = in.readLine()) != null && num > 0) {
                connectedCount += getCheckResult(line, osName);
                num--;
            }
            return connectedCount >= 2;
        } catch (Exception ex) {
            log.error("pingiputil error:", ex);
            return false;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("pingiputil close error:", e);
            }
        }
    }

    private static int getCheckResult(String line, String osName) {
        if (osName.contains("Windows")) {
            if (line.contains("TTL=")) {
                return 1;
            }
        } else {
            if (line.contains("ttl=")) {
                return 1;
            }
        }
        return 0;
    }


    public static String getHost(String address) {
        if(StringUtils.isEmpty(address)){
            return "";
        }
        if(address.length() < 7){
            return address;
        }
        int start = address.indexOf("://");
        String replace = address.replace("://", "...");
        int end = replace.indexOf(":");
        if(end <= start + 3){
            return address;
        }
        return address.substring(start + 3,end);
    }
}
